package pers.fulsun.es.test._04_search;

import java.io.IOException;
import java.util.List;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.elasticsearch.search.aggregations.metrics.ParsedSum;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import pers.fulsun.es.test._01_ESClient;

public class _011_ESTest_Doc_Search_Group {
  private static RestHighLevelClient client = _01_ESClient.getClient();

  public static void main(String[] args) throws IOException {
    // 构建查询的请求体
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    // 构建聚合查询方式
    TermsAggregationBuilder aggregationBuilder = AggregationBuilders
        .terms("age_tr").field("age").                   //桶分组
        //求总数: 可以从结果获取
        // subAggregation(AggregationBuilders.count("count_age").field("age")).
        subAggregation(AggregationBuilders.sum("sum_age").field("age")).  //求和
        subAggregation(AggregationBuilders.avg("avg_age").field("age")); //求平均值
    sourceBuilder.aggregation(aggregationBuilder);

    // 创建搜索请求对象
    SearchRequest request = new SearchRequest();
    // 不输出原始数据
    sourceBuilder.size(0);
    //  打印dsl语句
    System.out.println(("dsl:" + sourceBuilder.toString()));
    // 设置索引以及填充语句
    request.indices("user");
    request.source(sourceBuilder);
    // 发送请求
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);

    System.out.println("took:" + response.getTook());
    System.out.println("timeout:" + response.isTimedOut());
    System.out.println("aggregations========>>");
    // 和之前不同的是这里需要getAggregations获取聚合后的数据
    Aggregations aggregations = response.getAggregations();
    //ParsedTerms 有 long double String 三种类型
    ParsedLongTerms parsedStringTerms = aggregations.get("age_tr");
    List<? extends Bucket> buckets = parsedStringTerms.getBuckets();
    for (Terms.Bucket bucket : buckets) {
      //key的数据
      String key = bucket.getKey().toString();
      // 分组的数据 = count
      long docCount = bucket.getDocCount();
      //获取数据
      Aggregations bucketAggregations = bucket.getAggregations();
     // long count = ((ParsedValueCount) bucketAggregations.get("count_age")).getValue();
      ParsedSum sum = bucketAggregations.get("sum_age");
      ParsedAvg avg = bucketAggregations.get("avg_age");
      System.out.println(
          key + ": count:"
              + docCount + ", sum:"
              + sum.getValue() +  ", avg:"
              + avg.getValue());
    }

    // 关闭客户端连接
    client.close();
  }
}
